package com.yunda.nebula.gateway.sync.http;

import com.alibaba.fastjson.JSONObject;
import com.yunda.nebula.gateway.core.entity.ConfigData;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * \* User: wei.zhang
 * \* Date: 2020/9/16 16:53
 * \* Description:
 *
 * @author wei.zhang
 * \
 */
@Data
@Slf4j
public class DataRefreshFactory {
    private Map<String,DataRefresh> dataRefreshMap = new ConcurrentHashMap<>();

    public ConfigData cacheConfigData(String appId) {
        return dataRefreshMap.get(appId).cacheConfigData();
    }


    public boolean update(JSONObject data) {
        ConfigData configData = JSONObject.parseObject(JSONObject.toJSONString(data),ConfigData.class);
        log.info("开始执行更新缓存 ,任务ID为 {}",configData.getAppId());
        if (!dataRefreshMap.containsKey(configData.getAppId())){
            dataRefreshMap.put(configData.getAppId(),new AppDataRefresh());
        }
        return dataRefreshMap.get(configData.getAppId()).refresh(configData);
    }

    public boolean delete(JSONObject jsonObject) {
        ConfigData configData = JSONObject.parseObject(JSONObject.toJSONString(jsonObject),ConfigData.class);
        log.info("开始执行删除缓存任务 ,任务ID为 {}",configData.getAppId());
        DataRefresh dataRefresh = dataRefreshMap.get(configData.getAppId());
        if (dataRefresh != null){
            return dataRefresh.del();
        }
        return false;
    }
}
